
<script setup>
	
	import { onShow } from '@dcloudio/uni-app';
	import spellApi from '@/common/apis/spell';
	import { computed, ref, nextTick } from 'vue';
	import wordTrumpet from './components/trumpet.vue';
	import popupCard from './components/popup-card.vue';
	import wordTimedown from './components/timedown.vue';
	
	
	/** 导航栏 margin-right */
	const navRight = ref(0);
	
	// #ifdef MP-WEIXIN
	/** 获取小程序胶囊信息 */
	const { width } = uni.getMenuButtonBoundingClientRect()
	navRight.value = `${width}px`;
	// #endif
	
	
	/** 选择拼写模式弹窗实例 */
	const spellMode = ref(1);
	const selectModePopupRef = ref({});
	
	
	/** 拼写数据 */
	const spellData = uni.getStorageSync('_spell-data');
	
	/** 当前项索引 */
	const playIndex = ref(0);
	
	/** 词汇列表 */
	const vocabularylist = ref(uni.getStorageSync('_vocabulary-list'));
	
	/** current */
	const currentWord = computed(() => vocabularylist.value[playIndex.value]);
	
	/** 播放结束 */
	const playEnd = () => {
		vocabularylist.value[playIndex.value].play = false;
	};
	
	/** 监听自然结束 */
	uni.useAudio.onEnded(playEnd);
	
	/** 监听播放暂停 */
	uni.useAudio.onStop(playEnd);
	
	/** play word */
	const onPlayWord = () => {
		vocabularylist.value[playIndex.value].play = !vocabularylist.value[playIndex.value].play;
		uni.useAudio.src(currentWord.value?.voiceFile?.url);
		uni.useAudio.onEnded(playEnd);
	};
	
	/** 默认播放 */
	onPlayWord();
	
	/** collect */
	const onCollect = () => {
		vocabularylist.value[playIndex.value].collect = !vocabularylist.value[playIndex.value].collect;
	};
	
	/** 关闭上次播放状态、设置当前索引、播放当前单词 */
	const setCurrentIndex = index => {
		playEnd();
		playIndex.value = index;
		onPlayWord();
	};
	
	/** 上一个 */
	const onPrevious = () => {
		if (playIndex.value <= 0) {
			uni.$fui.toast('已经是第一个了哦~');
			return;
		};
		
		setCurrentIndex(playIndex.value - 1);
	};
	
	/** 下一个 */
	const onNext = () => {
		if (playIndex.value >= vocabularylist.value.length - 1) {
			uni.$fui.toast('已经是最后一个了哦~');
			return;
		};
		
		setCurrentIndex(playIndex.value + 1);
	};
	
	/** 拼写 */
	const onSpell = () => {
		uni.setStorageSync('_current-word', currentWord.value);
		uni.navigateTo({ 
			url: `/pages/course/spell/${spellMode.value === 1 ? 'spell' : 'filling'}` 
		});
	};
	
	
	/** 是否显示答题卡 */
	const showPopupCard = ref(false);
	
	/** 单词卡点击 */
	const hanldeCard = index => {
		setCurrentIndex(index);
		showPopupCard.value = false;
	};
	
	
	/** 结束并提交 */
	const endSubmit = async () => {
		const spellTime = vocabularylist.value.reduce((time, item) => time += (item.time || 0), 0);
		if (!spellTime) {
			uni.$fui.toast('暂无可提交的单词~');
			return;
		};
		
		await spellApi.saveWords({ words: vocabularylist.value.map(({ id, spell }) => ({ id, isSpell: spell ? 1 : 0 })), logId: spellData.logId });
		await spellApi.endSpell({ logId: spellData.logId, spellTime });
		uni.redirectTo({
			url: `/pages/course/spell/report?id=${spellData.logId}`,
			success: () => {
				uni.$fui.toast('提交成功~');
			}
		});
		// uni.navigateBack({ delta: 2, success: () => uni.$fui.toast('提交成功~') })
		uni.removeStorageSync('_spell-data');
		uni.removeStorageSync('_current-word');
		uni.removeStorageSync('_vocabulary-list');
	};
	
	
	/** 倒计时实例 */
	const wordTimedownRef = ref({});
	
	/** 进入页面时 */
	onShow(() => {
		const intervalTime = uni.getStorageSync('_interval') || 0;
		wordTimedownRef.value?.superpositionTime?.(+intervalTime);
		wordTimedownRef.value?.initFun?.();
		
		const spellTime = uni.getStorageSync('-spell-time');
		if (spellTime) {
			vocabularylist.value[playIndex.value].spell = true;
			vocabularylist.value[playIndex.value].time = +spellTime;
			uni.removeStorageSync('-spell-time');
			if (playIndex.value >= vocabularylist.value.length - 1) {
				showPopupCard.value = true;
				return;
			};
			
			setCurrentIndex(playIndex.value + 1);
		};
	});
	
	/** 总用时 */
	const totalTime = computed(() => vocabularylist.value.reduce((time, item) => time += (item.time || 0), 0));
	
	/** handle swiper */
	const handleSwiper = ({ detail }) => {
		setCurrentIndex(detail.current);
	};
	
	
	
</script>

<template>
	<view class="containerbox bgc-lg">
		<uv-navbar placeholder bg-color="transparent" auto-back>
			<template #right>
				<view :style="{ marginRight: navRight }" hover-class="opacity-70" class="transition-opacity flex">
					<view class="flex flex-column justify-center items-center mr-15">
						<image :src="`${$imageBaseUrl}time.png`" class="h-25" style="width: 58rpx" />
						<word-timedown size="18" :flash="false" ref="wordTimedownRef" />
					</view>
					
<!-- 					<view class="w-50 mr-15"> -->
					<view class="w-50 mr-10">
						<uv-image :src="`${$imageBaseUrl}card.png`" width="50rpx" height="50rpx" @tap="showPopupCard = true" />
					</view>
					
				<!-- 	<view class="mr-10 flex items-center justify-center mt-5" @tap="selectModePopupRef?.open">
						<uv-icon name="setting" size="42rpx" />
					</view> -->
				</view>
			</template>
		</uv-navbar>
		<progress :percent="(playIndex + 1) / vocabularylist.length * 100" backgroundColor="rgba(255,255,255,0.3)" activeColor="rgba(0,195,134,0.5)" border-radius="4" stroke-width="2" :active="true" active-mode="forwards" />
		
		<view class="flex items-center justify-between text-center mx-30 bgc-f4f9f3 round-20 px-90 py-30 mt-30">
			<view class="">
				<view class="text-24 text-9ca2a0">已学</view>
				<view class="bold mt-6 text-32">{{ vocabularylist.filter(item => item.spell).length }}</view>
			</view>
			
			<view class="">
				<view class="text-24 text-9ca2a0">未学</view>
				<view class="bold mt-6 text-32">{{ vocabularylist.filter(item => !item.spell).length }}</view>
			</view>
			
			<view class="">
				<view class="text-24 text-9ca2a0">总词数</view>
				<view class="bold mt-6 text-32">{{ vocabularylist.length }}</view>
			</view>
		</view>
		
		<swiper class="containerbox" :current="playIndex" @change="handleSwiper">
			<swiper-item v-for="item in vocabularylist" :key="item.id">
				<view class="mx-30 flex mt-210" @tap="onPlayWord">
					<view class="text-center m-auto">
						<view class="bold mt-20 text-80">{{ item.word }}</view>
						
						<view class="flex items-center justify-center text-26 my-20">
							<word-trumpet class="opacity-0" />
							{{ item.soundmark || '--' }}
							<word-trumpet :play="item?.play" />
						</view>
						
						<view class="text-26 px-20">{{ item.translation }}</view>
					</view>
				</view>
			</swiper-item>
		</swiper>
		
		
		<view class="flex items-center justify-between px-50 mt-auto pb-80 text-48">
			<view class="w-90 h-90 bgc-white round-30 flex items-center justify-center text-30 transition-bg" @tap="playIndex && onPrevious()" hover-class="opacity-70" :style="{ opacity: playIndex }">
				<uni-icons type="arrow-left" size="44rpx" class="flex items-center" />
			</view>
			
			<view class="w-90 h-90 bgc-white round-30 flex items-center justify-center selected transition-bg" hover-class="opacity-70" @tap="onSpell">
				<uv-icon name="edit-pen-fill" color="#00c386" size="48rpx" />
			</view>
			
			<view 
				hover-class="opacity-70" 
				@tap="playIndex !== vocabularylist.length - 1 && onNext()" 
				:style="{ opacity: playIndex === vocabularylist.length - 1 ? 0 : 1 }"
				class="w-90 h-90 bgc-white round-30 flex items-center justify-center text-30 transition-bg" 
			>
				<uni-icons type="arrow-right" size="44rpx" class="flex items-center" />
			</view>
		</view>
		
		<!-- 单词卡 -->
		<popup-card :list="vocabularylist" v-model="showPopupCard" @card="hanldeCard" @submit="endSubmit" :current="playIndex" />
		
		<!-- 选择拼写模式 -->
		<uv-popup ref="selectModePopupRef" :safe-area-inset-bottom="false" mode="bottom" round="32rpx">
			<view class="flex items-center justify-between pt-30 pb-40 px-30">
				<view class="text-36 font-weight-700">选择拼写模式</view>
				<uv-icon name="close" size="32rpx" @tap="selectModePopupRef.close" />
			</view>
			
			<view class="px-30 mt-20 pb-60">
				<view class="py-20 ml-20 border-bottom flex-between" @tap="spellMode = 1,selectModePopupRef.close()">
					<text :class="['text-30', { 'text-primary2': spellMode === 1 }]">默认拼写</text>
					<uv-icon name="checkbox-mark" size="32rpx" v-if="spellMode === 1" color="#1abc9c" />
				</view>
				
				<view class="py-20 ml-20 border-bottom flex-between" @tap="spellMode = 2,selectModePopupRef.close()">
					<text :class="['text-30', { 'text-primary2': spellMode === 2 }]">填空拼写</text>
					<uv-icon name="checkbox-mark" size="32rpx" v-if="spellMode === 2" color="#1abc9c" />
				</view>
			</view>
		</uv-popup>
	</view>
</template>


<style scoped lang="scss">
	.opacity-0{opacity: 0}
	.bgc-lg{background: linear-gradient(180deg,#c4f2e7, #f5f8e5, #f1f1f1)}
	.transition{transition: background-color .3s, border-color .3s}
	.transition-opacity{transition: opacity .3s}
	.mt-auto{margin-top: auto}
	.selected{color: #00c386}
	.bg-selected{background-color: #00c386}
	.mx-auto{margin-left: auto;margin-right: auto}
	.w-fit{width: fit-content}
	.mt-6{margin-top: 6rpx}
	.text-9ca2a0{color: #9ca2a0}
	.normal{font-weight: normal}
	.b-9ca2a0{border: 1rpx solid #c6d3cc}
	.bgc-f4f9f3{background-color: #f4f9f3}
	.bg-f0f0ee{background-color: #f0f0ee}
	.text-666{color: #666}
	.text-ababab{color: #ababab}
	.bg-not{background-color: #ff9900}
	.w-140{width: 140rpx}
	.h-140{height: 140rpx}
	.b-white{border: 1rpx solid white}
	.bg-fdfdfd{background-color: #fdfdfd}
	.button-selected{background-color: rgba(#00c386, .1);border-color: #00c386}
	.not-color-active{background-color: rgba(#ef945e, .1);border-color: #ef945e}
	.tip{top: 0;right: 0;color: #bdbcb8;background: linear-gradient(90deg, #ededeb, #f6f5f1)}
	.bg-ededeb{background-color: #ededeb}
	.text-a5a5a4{color: #a5a5a4}
	.opacity-70{opacity: .7}
	.pb-24{padding-bottom: 24rpx}
	.text-e16857{color: #e16857}
	.btn{height:80rpx;border-radius:12rpx;flex:1;text-align:center;line-height:80rpx;color:#fff;font-size:28rpx}
	.bg-577fff{background-color: #577fff}
	.text-577fff{color: #577fff}
	.w-160{width: 160rpx;flex: inherit}
	.transition-bg{transition: opacity .3s}
	.flipper {
		transition: transform 0.6s;
		transform-style: preserve-3d;
		position: relative;
	}
	.front, .back {
		backface-visibility: hidden;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}
	.front {
		z-index: 2;
	}
	.back {
		transform: rotateY(180deg);
		z-index: 1;
	}
	.open{
		transform: rotateY(180deg);
	}
	.mt-210{margin-top: 210rpx}
</style>